/**
 * 实时时钟（秒级）
 * - 格式：yyyy-MM-dd HH-mm-ss（注意分隔符为短横线按需求）
 */
export function useClock() {
  const now = ref<string>("");
  let timer: number | null = null;

  const pad = (n: number) => n.toString().padStart(2, "0");
  const format = (d: Date) => {
    const y = d.getFullYear();
    const M = pad(d.getMonth() + 1);
    const D = pad(d.getDate());
    const h = pad(d.getHours());
    const m = pad(d.getMinutes());
    const s = pad(d.getSeconds());
    return `${y}-${M}-${D} ${h}-${m}-${s}`;
  };

  const tick = () => {
    now.value = format(new Date());
  };

  const start = () => {
    if (timer !== null) return;
    tick();
    timer = window.setInterval(tick, 1000);
  };

  const stop = () => {
    if (timer !== null) {
      clearInterval(timer);
      timer = null;
    }
  };

  onMounted(start);
  onBeforeUnmount(stop);

  return { now, start, stop };
}

